import sys,os
from collections import defaultdict
def sortgff(chromtxt, fasta2, spe):
    chromsort = os.popen(f"cut -f 1 {chromtxt}").readlines()[0:25]
    scaffolds = os.popen(f"cut -f 1 hap2.fasta.fai").readlines()[25:]

    dic_fasta2 = {}
    name = "name"
    seq = "seq"
    for line in open(fasta2):
        if line.startswith(">"):
            dic_fasta2[name] = seq
            name = line.strip()[1:]
            seq = ""
        else:
            seq += line
    dic_fasta2[name] = seq
    print(dic_fasta2.keys())
    speprefix = spe
    out = open(f"{fasta2.split('.')[0]}.sort.fasta", "w")
    index = 1
    chromnum = 25
    for i in chromsort:
        # seq = str(fasta[dic[i]][0:].seq)
        # seq = format_seq(seq, 80)
        i = i.strip()
        seq = dic_fasta2[i]
        if index < 10 and index <= chromnum:
            out.write(f">{speprefix}Chr0{index}\n{seq}")
        elif index < 10 and index > chromnum:
            out.write(f">{speprefix}Scaffold0{index}\n{seq}")
        elif index >= 10 and index <= chromnum:
            out.write(f">{speprefix}Chr{index}\n{seq}")
        else:
            out.write(f">{speprefix}Scaffold{index}\n{seq}")
        index += 1
    for i in scaffolds:
        i = i.strip()
        out.write(f'>{i}\n{dic_fasta2[i]}')
if __name__ == "__main__":
    chromsort, fasta2, spe = sys.argv[1:]
    sortgff(chromsort, fasta2, spe)




